<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <!-- 使用el-row和el-col实现一行两列布局 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="数据类型" prop="dataType">
              <el-select v-model="formData.dataType" placeholder="请选择数据类型" style="width: 100%">
                <el-option label="正常生产" :value="1"/>
                <el-option label="返工" :value="2"/>
                <el-option label="试产" :value="3"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属日期" prop="scheduleDate">
              <el-date-picker clearable v-model="formData.scheduleDate" type="date" value-format="yyyy-MM-dd"
                              placeholder="选择所属日期" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产线" prop="deptId">
              <treeselect v-model="formData.deptId" :options="deptOptions" :flat="true" :normalizer="normalizer"
                          placeholder="选择产线" style="width: 100%" :default-expand-all="true" @select="handleDeptSelect"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作员" prop="operatorId">
              <el-select v-model="formData.operatorId" placeholder="请选择操作员" filterable style="width: 100%"
                         @change="changeUser">
                <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10">
          <el-col :span="12">
            <el-form-item label="开始时间" prop="startDateTime">
              <el-date-picker clearable v-model="formData.startDateTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择开始时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="endDateTime">
              <el-date-picker clearable v-model="formData.endDateTime" type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择结束时间" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as LinManHourApi from '@/api/lamp/linmanhour';
import * as ScheduleApi from '@/api/lamp/schedule/index.js';
import {listDept} from '@/api/system/dept';
import {listUser} from '@/api/system/user';
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "LinManHourForm",
  components: {Treeselect},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        dataType: undefined,
        scheduleId: undefined,
        scheduleDate: undefined,
        deptId: undefined,
        deptName: undefined,
        startDateTime: undefined,
        endDateTime: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
      },
      // 表单校验
      formRules: {
        dataType: [{required: true, message: '数据类型1-正常生产2-返工3-试产不能为空', trigger: 'change'}],
        operatorIdCard: [{required: true, message: '操作员工号不能为空', trigger: 'blur'}],
        scheduleId: [{required: true, message: '排班不能为空', trigger: 'change'}],
        deptId: [{required: true, message: '产线不能为空', trigger: 'change'}],
        operatorId: [{required: true, message: '操作员不能为空', trigger: 'change'}],
      },
      // 产线树选项
      deptOptions: [],
      // 用户列表
      userList: [],
      // 排班列表
      scheduleList: [],
    };
  },
  created() {
    this.getOptions();
  },
  methods: {
    changeUser(e) {
      const user = this.userList.find(item => item.id === e);
      this.formData.operatorName = user.username;
      this.formData.operatorIdCard = user.idCard;
    },
    /** 获取下拉框选项 */
    async getOptions() {
      try {
        // 获取所有产线列表（包括所有层级）
        const deptRes = await listDept({pageNo: 1, pageSize: 100});
        // 处理产线树数据
        this.deptOptions = this.addLevelToNodes(this.handleTree(deptRes.data, "id"), 1);

        // 获取用户列表
        const userRes = await listUser({pageSize: 100, pageNo: 1});
        this.userList = userRes.data.list;

        // 获取排班列表
        // const scheduleRes = await ScheduleApi.getSchedulePage({pageNo: 1, pageSize: 100});
        // this.scheduleList = scheduleRes.data.list;
      } catch (error) {
        this.$modal.msgError('获取数据失败');
      }
    },
    // 递归函数为节点添加层级标记
    addLevelToNodes(nodes, currentLevel = 1) {
      if (!nodes || !Array.isArray(nodes)) {
        return [];
      }
      return nodes.map(node => {
        const newNode = {
          ...node,
          level: currentLevel
        };
        if (node.children && node.children.length > 0) {
          newNode.children = this.addLevelToNodes(node.children, currentLevel + 1);
        }
        return newNode;
      });
    },

    // 产线树数据格式化 - 参考deviceBind页面的实现
    normalizer(node) {
      // 构建基础对象，确保包含 id, label, children 属性
      const normalizedNode = {
        id: node.id,
        label: node.name,
        children: node.children
      };

      // 关键：如果不是type==3的产线，则禁用
      if (node.deptType !== 3) {
        normalizedNode.isDisabled = true;
      }
      return normalizedNode;
    },

    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 设置所属日期默认今天
      this.formData.scheduleDate = this.formatDate(new Date());
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await LinManHourApi.getLinManHour(id);
          this.formData = res.data;
          this.dialogTitle = "修改产线工时";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增产线工时";
      }
    },

    /** 处理产线选择 */
    handleDeptSelect(deptId) {
      if (deptId) {
        this.formData.deptName = deptId.name;
      }
    },

    /** 格式化日期为 yyyy-MM-dd */
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await LinManHourApi.updateLinManHour(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await LinManHourApi.createLinManHour(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        dataType: undefined,
        scheduleId: undefined,
        scheduleDate: undefined,
        deptId: undefined,
        deptName: undefined,
        startDateTime: undefined,
        endDateTime: undefined,
        operatorId: undefined,
        operatorName: undefined,
        operatorIdCard: undefined,
      };
      this.resetForm("formRef");
    }
  }
};
</script>

